// src/stores/system.ts
import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';

export const useSystemStore = defineStore('system', () => {
  // 使用 useStorage 持久化到 localStorage
  const storageSystem = useStorage('system-setting', {
    logoUrl: '',
    systemName: '统一认证平台',
    internetLabTitle: '统一认证平台'
  });

  // 响应式状态
  const logoUrl = ref(storageSystem.value.logoUrl);
  const systemName = ref(storageSystem.value.systemName);
  const internetLabTitle = ref(storageSystem.value.internetLabTitle);

  // 修改方法
  function setLogoUrl(url: string) {
    logoUrl.value = url;
    storageSystem.value.logoUrl = url; // 同步到 localStorage
    setFavicon(url);
  }

  function setSystemName(name: string) {
    systemName.value = name;
    storageSystem.value.systemName = name; // 同步到 localStorage
  }
  function setTitle(name: string) {
    internetLabTitle.value = name;
    storageSystem.value.internetLabTitle = name; // 同步到 localStorage
    setPageTitle(name);
  }

  function setFavicon(url: string) {
    let link: HTMLLinkElement | null = document.querySelector("link[rel~='icon']");
    if (!link) {
      link = document.createElement('link');
      link.rel = 'icon';
      document.getElementsByTagName('head')[0].appendChild(link);
    }
    link.href = url;
  }
  // 动态修改网页标题
  function setPageTitle(title: string) {
    if (!title) return;

    // 如果不存在 <title> 标签，就创建一个
    let titleEl = document.querySelector('title');
    if (!titleEl) {
      titleEl = document.createElement('title');
      document.head.appendChild(titleEl);
    }

    // 更新标题内容
    titleEl.textContent = title;
    document.title = title; // 兼容性保险写法
  }
  return {
    logoUrl,
    systemName,
    internetLabTitle,
    setLogoUrl,
    setSystemName,
    setTitle,
    setFavicon,
    setPageTitle
  };
});
